<template>
  <view class="repair-detail">
    <!-- 顶部导航 -->
    <view class="nav-bar">
      <view class="back-btn" @click="backPage()">
        <view class="back-icon"></view>
      </view>
      <view class="title">详情</view>
      <view class="right-icons">
        <text class="iconfont">&#xe601;</text>
      </view>
    </view>

    <!-- 维修信息 -->
    <view class="info-section">
      <view class="section-title">维修信息</view>
      <view class="info-list">
        <view class="info-item">
          <text class="label">维修单号:</text>
          <text class="value">{{ repairInfo.repairNo }}</text>
        </view>
        <view class="info-item">
          <text class="label">车主姓名:</text>
          <text class="value">{{ repairInfo.ownerName }}</text>
        </view>
        <view class="info-item">
          <text class="label">联系方式:</text>
          <text class="value clickable" @tap="makePhoneCall">{{ repairInfo.phone }}</text>
        </view>
        <view class="info-item">
          <text class="label">维修方式:</text>
          <text class="value">{{ repairInfo.repairType }}</text>
        </view>
        <view class="info-item">
          <text class="label">取车位置:</text>
          <text class="value clickable location" @tap="openLocation">{{ repairInfo.location }}</text>
        </view>
        <view class="info-item">
          <text class="label">预约日期:</text>
          <text class="value">{{ repairInfo.appointmentDate }}</text>
        </view>
     <!--   <view class="info-item">
          <text class="label">提交日期:</text>
          <text class="value">{{ repairInfo.submitDate }}</text>
        </view> -->
		<view class="info-item">
		  <text class="label">预约店铺:</text>
		  <text class="value">{{ repairInfo.reserved1}}</text>
		</view>
		<!-- <view>{{repairInfo.status}}</view> -->
		<!-- 状态 -->
      </view>
    </view>

    <!-- 车辆信息 -->
    <view class="info-section">
      <view class="section-title">车辆信息</view>
      <view class="info-list">
       <view class="info-item">
          <text class="label">车辆类型:</text>
          <text class="value">{{ carInfo.carTypeId }}</text>
        </view>
        <view class="info-item">
          <text class="label">车牌号:</text>
          <text class="value">{{ carInfo.carNum }}</text>
        </view>
        <view class="info-item" v-if="carInfo.vehiclePhotos.length">
          <text class="label">整车照片:</text>
        </view>
        <view class="image-preview" v-if="carInfo.vehiclePhotos.length">
          <image v-for="(img, idx) in carInfo.vehiclePhotos" :key="idx" :src="img" mode="aspectFit"
            @tap="previewImage(img, carInfo.vehiclePhotos)" />
        </view>
        <view class="info-item" v-if="carInfo.repairPhotos.length">
          <text class="label">维修部位照片:</text>
        </view>
        <view class="image-grid" v-if="carInfo.repairPhotos.length">
          <image v-for="(img, idx) in carInfo.repairPhotos" :key="idx" :src="img" mode="aspectFill"
            @tap="previewImage(img, carInfo.repairPhotos)" />
        </view>
      </view>
    </view>
  <!--    <view class="info-item">
              <text class="label">当前状态:</text>
              <text class="value">{{ statusText }}</text>
            </view> -->
    <!-- 底部按钮 -->
    <view v-if="repairInfo.status===0" class="bottom-button" :class="{ disabled: arrived }" @tap="confirmArrival">
      {{ arrived ? '已到场' : '确认到场' }}
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import request from '@/pages/util/request.js';
import baseUrl from '@/pages/util/urlConfig.js';
// 状态管理
const arrived = ref(false)

// 数据模型
const repairInfo = ref({
  repairNo: '',
  ownerName: '',
  phone: '',
  repairType: '',
  location: '',
  appointmentDate: '',
  submitDate: '',
  status:0,
  reserved1:''//店铺名
})

const carInfo = ref({
  carTypeId: '',
  carNum: '',
  vehiclePhotos: [],
  repairPhotos: []
})

// 生命周期钩子 - 页面加载时获取数据
onLoad((options) => {
  console.log("详情页 onLoad 接收到的 options:", options);
  if (options && options.taskData) {
    try {
      const task = JSON.parse(decodeURIComponent(options.taskData));
      console.log("解析后的任务数据:", task);
  
      if (!task || typeof task !== 'object' || !task.id) {
        console.error('无效或不完整的任务数据:', task);
        uni.showToast({
          title: '加载任务数据失败',
          icon: 'none'
        });
        return;
      }

      // 更新维修信息
      repairInfo.value = {
        repairNo: task.id || '',
        ownerName: task.name || '',
        phone: task.phone || '',
        repairType: task.type || '',
        location: task.location || '',
        appointmentDate: task.reservationTime || '',
        submitDate: task.createTime || '' ,// 假设 createTime 是提交日期,
		status:task.status ,
		reserved1:task.reserved1 || ''
      };

      // 更新车辆信息 (完善图片处理逻辑)
      let repairPhotosArr = [];
      if (task.repairPhotos) {
        if (Array.isArray(task.repairPhotos)) {
          repairPhotosArr = task.repairPhotos;
        } else if (typeof task.repairPhotos === 'string') {
          repairPhotosArr = task.repairPhotos.includes(',')
            ? task.repairPhotos.split(',').map(s => s.trim()).filter(Boolean)
            : (task.repairPhotos ? [task.repairPhotos] : []);
        }
      }

      let vehiclePhotosArr = [];
      if (task.vehiclePhotos) {
        if (Array.isArray(task.vehiclePhotos)) {
          vehiclePhotosArr = task.vehiclePhotos;
        } else if (typeof task.vehiclePhotos === 'string') {
          vehiclePhotosArr = task.vehiclePhotos.includes(',')
            ? task.vehiclePhotos.split(',').map(s => s.trim()).filter(Boolean)
            : (task.vehiclePhotos ? [task.vehiclePhotos] : []);
        }
      }

      carInfo.value = {
        carTypeId: task.carTypeId || '',
        carNum: task.carNum || '',
        vehiclePhotos: vehiclePhotosArr,
        repairPhotos: repairPhotosArr
      };

      console.log('更新后的维修信息:', repairInfo.value);
      console.log('更新后的车辆信息:', carInfo.value);

    } catch (e) {
      console.error("解析任务数据失败:", e);
      uni.showToast({
        title: '数据解析错误',
        icon: 'none'
      });
    }
  } else {
    console.warn('未接收到任务数据');
    uni.showToast({
        title: '未找到任务信息',
        icon: 'none'
    });
  }
});

// 页面方法
const backPage = () => {
  uni.navigateBack()
}

// 拨打电话
const makePhoneCall = () => {
  if (!repairInfo.value.phone) {
    uni.showToast({
      title: '电话号码不存在',
      icon: 'none'
    })
    return
  }
  uni.makePhoneCall({
    phoneNumber: repairInfo.value.phone
  })
}

// 打开位置
const openLocation = () => {
  if (!repairInfo.value.location) {
    uni.showToast({
      title: '位置信息不存在',
      icon: 'none'
    })
    return
  }
  uni.showToast({
    title: '打开位置信息',
    icon: 'none'
  })
}

// 预览图片
const previewImage = (current, urls) => {
  if (!current) {
    uni.showToast({
      title: '图片不存在',
      icon: 'none'
    })
    return
  }
  uni.previewImage({
    current,
    urls: urls || [current]
  })
}

// 确认到场
const confirmArrival = () => {
  if (arrived.value) return
  uni.showModal({
    title: '确认到场',
    content: '是否确认到场？',
    success: (res) => {
      if (res.confirm) {
        const id = repairInfo.value.repairNo;
		const phone =repairInfo.value.phone;
        const url = baseUrl+`/qxk/reservation/up/${id}/${phone}`;
		console.log(phone);
        request({
          url: url,
          method: 'PUT',
          success: (response) => {
            if (response.statusCode === 200) {
              arrived.value = true;
              uni.showToast({
                title: '已确认到场',
                icon: 'success'
              });
              // 更新本地状态中的 status 值
              repairInfo.value.status = 2;
            } else {
              uni.showToast({
                title: '更新状态失败',
                icon: 'none'
              });
            }
          },
          fail: (error) => {
            console.error('请求失败:', error);
            uni.showToast({
              title: '请求失败，请稍后重试',
              icon: 'none'
            });
          }
        });
      }
    }
  });
}
</script>


<style lang="scss">
.repair-detail {
		min-height: 100vh;
		background-color: #f5f5f5;
		padding-bottom: 100rpx;

		.nav-bar {
			background-color: #007AFF;
			color: #fff;
			padding: 44px 16px 10px;
			display: flex;
			align-items: center;


			.title {
				flex: 1;
				text-align: center;
				font-size: 18px;
			}

			.right-icons {
				width: 24px;
			}
		}

		.info-section {
			margin: 20rpx;
			background-color: #fff;
			border-radius: 12rpx;
			padding: 30rpx;

			.section-title {
				font-size: 32rpx;
				font-weight: bold;
				margin-bottom: 30rpx;
			}

			.info-list {
				.info-item {
					display: flex;
					margin-bottom: 20rpx;

					.label {
						color: #666;
						width: 160rpx;
					}

					.value {
						flex: 1;
						color: #333;

						&.clickable {
							color: #007AFF;
						}

						&.location {
							display: flex;
							align-items: center;

							&::after {
								content: '';
								width: 32rpx;
								height: 32rpx;
								margin-left: 10rpx;
							}
						}
					}
				}
			}
		}

		.image-preview {
			width: 100%;
			height: 300rpx;
			margin: 20rpx 0;

			image {
				width: 100%;
				height: 100%;
				border-radius: 8rpx;
			}
		}

		.image-grid {
			display: flex;
			flex-wrap: wrap;
			gap: 20rpx;

			image {
				width: calc((100% - 40rpx) / 3);
				height: 200rpx;
				border-radius: 8rpx;
			}
		}

		.bottom-button {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			height: 100rpx;
			background-color: #007AFF;
			color: #fff;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 32rpx;

			&.disabled {
				background-color: #999 !important;
				color: #fff !important;
				pointer-events: none;
			}
		}
	}

	.back-btn {
		margin-left: 20rpx;
		width: 50rpx;
		height: 50rpx;
		position: relative;
	}

	.back-icon {
		width: 30px;
		height: 30px;
	}

	.back-icon::before {
		content: "";
		position: absolute;
		width: 20px;
		height: 2px;
		background-color: #fff;
		top: 10rpx;
		left: 47rpx;
		transform: translate(-50%, -50%);
	}

	.back-icon::after {
		content: "";
		position: absolute;
		width: 10px;
		height: 10px;
		border-left: 2px solid #fff;
		border-bottom: 2px solid #fff;
		transform: rotate(45deg);
		top: 0rpx;
		left: 30rpx;
	}
</style>